/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.identifier;

import at.schauer.gregor.vienna.exception.IdentifierGenerationException;

/**
 * @author Gregor Schauer
 */
public class SequenceGenerator<O> extends CachedGenerator<Long, O> {
	protected long min;
	protected long max;
	protected long current;
	protected long increment;
	protected boolean cycle;

	public SequenceGenerator() {
		this(0L, 1L);
	}

	public SequenceGenerator(long current, long increment) {
		this(1L, Long.MAX_VALUE, current, increment, false);
	}

	public SequenceGenerator(long min, long max, long current, long increment, boolean cycle) {
		this.min = min;
		this.max = max;
		this.current = current;
		this.increment = increment;
		this.cycle = cycle;
	}

	@Override
	protected synchronized Long newIdentifier(O obj) {
		current += increment;
		if (current > max || current < min) {
			if (!cycle) {
				throw new IdentifierGenerationException("Cannot generate identifier for " + obj);
			}
			return current = increment < 0L ? max : min;
		}
		return current;
	}
}
